#include <iostream>
#include <string>
#include <functional>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
using namespace std;

using wsserver_t = websocketpp::server<websocketpp::config::asio>;

void http_callback(wsserver_t* wsserver,websocketpp::connection_hdl hdl)
{
    //给用户返回一个hello world界面
    wsserver_t::connection_ptr conn = wsserver->get_con_from_hdl(hdl);
    std::cout<<"body: "<<conn->get_request_body()<<std::endl;
    websocketpp::http::parser::request req = conn->get_request();
    std::cout<<"uri: "<<req.get_uri()<<std::endl;
    std::cout<<"method: "<<req.get_method()<<std::endl;
    std::string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(conn->get_request_body());
    //conn->set_body(body);
    //conn->append_header("Content-Type","text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}
void open_callback(wsserver_t* wsserver,websocketpp::connection_hdl hdl)
{
    cout<<"握手成功"<<endl;
}

void close_callback(wsserver_t* wsserver,websocketpp::connection_hdl hdl)
{
    cout<<"连接断开"<<endl;
}

void message_callback(wsserver_t* wsserver,websocketpp::connection_hdl hdl,wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn = wsserver->get_con_from_hdl(hdl);
    std::cout<<"wsserver message: "<<msg->get_payload()<<std::endl;
    std::string resp = "client say: "+msg->get_payload();
    conn->send(resp,websocketpp::frame::opcode::text);
}

int main()
{
    //使用websocket创建服务器
    wsserver_t wsserver;
    //设置日志等级
    wsserver.set_access_channels(websocketpp::log::alevel::none);
    //设置调度器asio
    wsserver.init_asio();
    //设置回调函数
    wsserver.set_http_handler(bind(http_callback,&wsserver,std::placeholders::_1));
    wsserver.set_open_handler(bind(open_callback,&wsserver,std::placeholders::_1));
    wsserver.set_close_handler(bind(close_callback,&wsserver,std::placeholders::_1));
    wsserver.set_message_handler(bind(message_callback,&wsserver,std::placeholders::_1,std::placeholders::_2));
    //监听
    wsserver.listen(3389);
    //建立新连接
    wsserver.start_accept();
    //启动服务器
    wsserver.run();
    return 0;
}